/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.articles.importFromLn.updates;

import cz.mzk.kramerius.commons.Dom4jUtils;
import cz.mzk.kramerius.commons.Namespaces;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.QName;
import org.dom4j.XPath;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class DcTypeUpdater implements DatastreamUpdater {

    private static final XPath dcTypeXpath = Dom4jUtils.createXPath("oai_dc:dc/dc:type");
    private static final XPath rootXpath = Dom4jUtils.createXPath("oai_dc:dc");
    public static final String NEW_DC_TYPE_VALUE = "model:article";

    @Override
    public Document update(Document src) {
        removeAllDcTypeElements(src);
        addNewDcTypeElement(src);
        return src;
    }

    private void removeAllDcTypeElements(Document src) {
        List<Node> nodes = dcTypeXpath.selectNodes(src);
        for (Node node : nodes) {
            node.detach();
        }
    }

    private void addNewDcTypeElement(Document src) {
        Element root = (Element) rootXpath.selectSingleNode(src);
        Element dcType = root.addElement(new QName("type", Namespaces.dc));
        dcType.addText(NEW_DC_TYPE_VALUE);
    }
}
